package cn.zwxky.android.staff.BusinessAddList;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.zgscwjm.lsfbbasetemplate.Event.EventAnnotation;
import com.zgscwjm.lsfbbasetemplate.LsfbActivity;
import com.zgscwjm.lsfbbasetemplate.annotation.ContentView;
import com.zgscwjm.lsfbbasetemplate.annotation.OnClick;
import com.zgscwjm.lsfbbasetemplate.annotation.ViewInject;
import com.zgscwjm.lsfbbasetemplate.config.Config;
import com.zgscwjm.lsfbbasetemplate.internet.BaseInternet;
import com.zgscwjm.lsfbbasetemplate.net.HttpClient;
import com.zgscwjm.lsfbbasetemplate.utils.DensityUtils;
import com.zgscwjm.lsfbbasetemplate.utils.LsfbLog;
import com.zgscwjm.lsfbbasetemplate.utils.SN;
import com.zgscwjm.lsfbbasetemplate.utils.T;
import com.zgscwjm.lsfbbasetemplate.view.Camera.LsfbCamera;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.zwxky.android.staff.Login.ForgetBean;
import cn.zwxky.android.staff.R;
import cn.zwxky.android.staff.Utils.LittleUtils;
import cn.zwxky.android.staff.Utils.NoDoubleClickUtils;
import cn.zwxky.android.staff.Utils.Permission;
import cn.zwxky.android.staff.Utils.PictureActivity;
import cn.zwxky.android.staff.Utils.PopWindowManager;
import cn.zwxky.android.staff.Utils.PopWindowManager2;
import cn.zwxky.android.staff.Utils.URLString;
import cn.zwxky.android.staff.Utils.ZipPic;
import cn.zwxky.android.staff.Utils.chooseimg.ChooseMoreImage;
import cn.zwxky.android.staff.Utils.chooseimg.DuoTuEvent;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;


/**
 * 业务添加
 * Created by Administrator on 2017/3/21 0021.
 */
@ContentView(R.layout.aty_business_add)
public class BusinessAddActivity extends LsfbActivity {

    /**
     * 项目类型
     */
    @ViewInject(R.id.aty_business_text_select)
    private TextView text_select;

    /**
     * 项目名称
     */
    @ViewInject(R.id.aty_business_et_project)
    private EditText et_project;

    /**
     * 姓名
     */
    @ViewInject(R.id.aty_business_et_name)
    private EditText et_name;

    /**
     * 电话
     */
    @ViewInject(R.id.aty_business_et_phone)
    private EditText et_phone;

    /**
     * 公司名称
     */
    @ViewInject(R.id.aty_business_et_gongsi)
    private EditText et_gongsi;

    /**
     * 备注
     */
    @ViewInject(R.id.aty_business_et_beizhu)
    private EditText et_beizhu;

    @ViewInject(R.id.aty_text_file_name)
    private TextView text_file_name;


    /**
     * 三张图片
     */
    @ViewInject(R.id.aty_img_photo1)
    private SimpleDraweeView img_photo1;

    @ViewInject(R.id.aty_img_photo2)
    private SimpleDraweeView img_photo2;

    @ViewInject(R.id.aty_img_photo3)
    private SimpleDraweeView img_photo3;


    /**
     * PopWindow管理类
     */
    private PopWindowManager replay;

    private String id = "";

    private List<TypeBean.ListBean> mList;
    /**
     * RecyclerView的布局管理器
     */
    private RecyclerView.LayoutManager mlayoutManager;

    private TypeAdapter adapter;

    private String type_name;
    private String type_id = "";

    private String file = "";
    private String file_name = "";

    private Uri mUri;
    private String img_s = "";
    private int RESULT_CIR_IMAGE = 200;
    private int img_number=0;

    private String img1="";
    private String img2="";
    private String img3="";

    private Handler handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);

            switch (msg.what) {
                case 1000:
                    adapter.notifyDataSetChanged();
                    break;
                case 2000:
                    text_select.setText(type_name);
                    break;
                case 3000:
                    text_file_name.setText("文件：" + file_name + "  已上传");
                    break;
            }
        }
    };

    @Override
    public void initView() {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

        Permission permission = new Permission(BusinessAddActivity.this);
        permission.GetCAMEARPermission();

        LittleUtils.setsimpletitlebar(this, "业务上传");
        TextView textView = new TextView(this);
        textView.setText("提交");
        textView.setTextColor(getResources().getColor(R.color.white_color));
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //收起软键盘
                InputMethodManager imm2 = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm2.hideSoftInputFromWindow(et_project.getWindowToken(), 0);
                imm2.hideSoftInputFromWindow(et_name.getWindowToken(), 0);
                imm2.hideSoftInputFromWindow(et_phone.getWindowToken(), 0);
                imm2.hideSoftInputFromWindow(et_gongsi.getWindowToken(), 0);
                imm2.hideSoftInputFromWindow(et_beizhu.getWindowToken(), 0);
                if (!NoDoubleClickUtils.isDoubleClick()) {
                    post();
                }
            }
        });
        getTitleBar().setRightView(textView, 0, 0, DensityUtils.dp2px(this, 10), 0);

        mList = new ArrayList<>();
        adapter = new TypeAdapter(BusinessAddActivity.this, mList, R.layout.item_pop_select_type);
        id = getIntent().getStringExtra("id");
        if (!id.equals("-1")) {
            getData();
        }
    }


    @Override
    public void initEvent() {

    }

    /**
     * 点击事件
     *
     * @param view
     */
    @OnClick({R.id.aty_business_select, R.id.aty_business_btn_post, R.id.aty_img_add,R.id.aty_img_photo1,R.id.aty_img_photo2,R.id.aty_img_photo3})
    public void onClick(View view) {
        switch (view.getId()) {
            //项目类型选择
            case R.id.aty_business_select:
                for (TypeBean.ListBean dataBean : mList) {
                    dataBean.check = false;
                }
                replay = new PopWindowManager(BusinessAddActivity.this, R.layout.pop_select_type) {
                    @Override
                    public void onViewLister(View contentView, final PopWindowManager manager) {

                        final TextView pop_select_quxiao = (TextView) contentView.findViewById(R.id.pop_select_quxiao);
                        final TextView pop_select_yes = (TextView) contentView.findViewById(R.id.pop_select_yes);
                        final RecyclerView dish_list = (RecyclerView) contentView.findViewById(R.id.dish_list);
                        final RelativeLayout RelativeLayout = (RelativeLayout) contentView.findViewById(R.id.RelativeLayout);

                        mlayoutManager = new LinearLayoutManager(BusinessAddActivity.this);//布局模式为listview方式
                        dish_list.setLayoutManager(mlayoutManager);
                        dish_list.setAdapter(adapter);

                        pop_select_quxiao.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                type_id = "";
                                manager.hideWindow();
                            }
                        });

                        pop_select_yes.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                handler.sendEmptyMessage(2000);
                                manager.hideWindow();
                            }
                        });

                        RelativeLayout.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                manager.hideWindow();
                            }
                        });

                    }
                };
                replay.showWindowsCenter(BusinessAddActivity.this.getWindow().getDecorView());
                break;
            //文件上传
            case R.id.aty_business_btn_post:
                startActivity(new Intent(this, FileUploadingActivity.class));
                break;
            //照片上传
            case R.id.aty_img_add:
                LsfbLog.e("图片来源选择");
                PopWindowManager2 popWindowManager = new PopWindowManager2(this,
                        R.layout.pop_selectcamrea) {
                    LsfbCamera mLsfbCamera = new LsfbCamera() {
                        @Override
                        public void resultUri(Uri uri) {
                            mUri = uri;
                        }
                    };

                    @Override
                    public void onViewLister(View contentView, final PopWindowManager2 manager) {
                        contentView.findViewById(R.id.pop_selectcamrea).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mLsfbCamera.setActivity(BusinessAddActivity.this);
                                mLsfbCamera.gotoCamera();
                                manager.hideWindow();
                            }
                        });
                        contentView.findViewById(R.id.pop_selectphoto).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                startActivity(new Intent(BusinessAddActivity.this, ChooseMoreImage.class).putExtra("num", 3).putExtra("url", URLString.IMGUPLOAD));
                                manager.hideWindow();
                            }
                        });
                        contentView.findViewById(R.id.pop_bank).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                manager.hideWindow();
                            }
                        });

                    }
                };
                popWindowManager.showWindows(getWindow().getDecorView());
                popWindowManager.backgroundAlpha(this, 0.7f);
                break;
            case R.id.aty_img_photo1:
                startActivity(new Intent(this, PictureActivity.class).putExtra("url",img1));
                break;
            case R.id.aty_img_photo2:
                startActivity(new Intent(this, PictureActivity.class).putExtra("url",img2));
                break;
            case R.id.aty_img_photo3:
                startActivity(new Intent(this, PictureActivity.class).putExtra("url",img3));
                break;
        }
    }

    @EventAnnotation
    public void TypeClickEvent(TypeClickEvent event) {
        for (TypeBean.ListBean dataBean : mList) {
            dataBean.check = false;
            if (dataBean.getId().equals(event.getData())) {
                dataBean.check = true;
                type_name = dataBean.getName();
                type_id = dataBean.getId();
            }
        }
//        handler.sendEmptyMessage(1000);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void initData() {
        getType();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getType();
    }

    /**
     * 获取类型
     */
    public void getType() {
        HashMap<String, String> hashMap = new HashMap<String, String>();
        hashMap.put("uid", Config.getUserId());
        new BaseInternet().getData_Get(URLString.SERVICE_TYPE, hashMap, TypeBean.class, new TypeEvent<TypeBean>(), true, true);
    }

    @EventAnnotation
    public void TypeEvent(TypeEvent<TypeBean> event) {
        switch (event.getCode()) {
            case 200:
                mList.clear();
                mList.addAll(event.getData().getList());
                adapter.notifyDataSetChanged();
                break;
            default:
                break;
        }
    }


    /**
     * 获取业务
     */
    public void getData() {
        HashMap<String, String> hashMap = new HashMap<String, String>();
        hashMap.put("uid", Config.getUserId());
        hashMap.put("id", id);
        new BaseInternet().getData(URLString.SERVICE_DET, hashMap, BusinessAddBean.class, new BusinessAddEvent<BusinessAddBean>(), false);
    }

    @EventAnnotation
    public void BusinessAddEvent(BusinessAddEvent<BusinessAddBean> event) {
        switch (event.getCode()) {
            case 200:
                type_id = event.getData().getClas();
                text_select.setText(event.getData().getClas_name());
                et_project.setText(event.getData().getTitle());
                et_name.setText(event.getData().getName());
                et_phone.setText(event.getData().getTel());
                et_gongsi.setText(event.getData().getCompany());
                et_beizhu.setText(event.getData().getContent());
                if (!event.getData().getFiles().isEmpty()) {
                    text_file_name.setText("已上传文件");
                }
                if (event.getData().getImgs().isEmpty()) {
                    img_photo1.setVisibility(View.INVISIBLE);
                    img_photo2.setVisibility(View.INVISIBLE);
                    img_photo3.setVisibility(View.INVISIBLE);
                } else {
                    String[] img = event.getData().getImgs().split(",");
                    if (img.length == 1) {
                        img_photo1.setVisibility(View.VISIBLE);
                        img_photo2.setVisibility(View.INVISIBLE);
                        img_photo3.setVisibility(View.INVISIBLE);
                        img_photo1.setImageURI(Uri.parse(URLString.IMG_URL + img[0]));
                        img1=img[0];
                    }else if (img.length == 2) {
                        img_photo1.setVisibility(View.VISIBLE);
                        img_photo2.setVisibility(View.VISIBLE);
                        img_photo3.setVisibility(View.INVISIBLE);
                        img_photo1.setImageURI(Uri.parse(URLString.IMG_URL + img[0]));
                        img_photo2.setImageURI(Uri.parse(URLString.IMG_URL + img[1]));
                        img1=img[0];
                        img2=img[1];
                    }else if (img.length == 3) {
                        img_photo1.setVisibility(View.VISIBLE);
                        img_photo2.setVisibility(View.VISIBLE);
                        img_photo3.setVisibility(View.VISIBLE);
                        img_photo1.setImageURI(Uri.parse(URLString.IMG_URL + img[0]));
                        img_photo2.setImageURI(Uri.parse(URLString.IMG_URL + img[1]));
                        img_photo3.setImageURI(Uri.parse(URLString.IMG_URL + img[2]));
                        img1=img[0];
                        img2=img[1];
                        img3=img[2];
                    }
                }
                break;
            default:
                break;
        }
    }

    /**
     * 上传业务
     */
    public void post() {
        HashMap<String, String> hashMap = new HashMap<String, String>();

        if (text_select.getText().toString().equals("请选择上传类型")) {
            SN.SnackShow(text_select, "请选择上传类型");
            return;
        }
        if (et_project.getText().toString().isEmpty()) {
            SN.SnackShow(text_select, "请输入项目名称");
            return;
        }
        if (et_name.getText().toString().isEmpty()) {
            SN.SnackShow(text_select, "请输入姓名");
            return;
        }
        if (et_phone.getText().toString().isEmpty()) {
            SN.SnackShow(text_select, "请输入电话");
            return;
        }
        if (et_gongsi.getText().toString().isEmpty()) {
            SN.SnackShow(text_select, "请输入公司名称");
            return;
        }
//        if (et_beizhu.getText().toString().isEmpty()) {
//            SN.SnackShow(text_select, "请输入备注");
//            return;
//        }

        if (!id.equals("-1")) {
            hashMap.put("id", id);
        }
        hashMap.put("uid", Config.getUserId());

        hashMap.put("clas", type_id);
        hashMap.put("title", et_project.getText().toString());
        hashMap.put("name", et_name.getText().toString());
        hashMap.put("tel", et_phone.getText().toString());
        hashMap.put("company", et_gongsi.getText().toString());
        hashMap.put("content", et_beizhu.getText().toString());
        if (!file.isEmpty()) {
            hashMap.put("files", file);
        }
        if (!img_s.isEmpty()) {
            hashMap.put("imgs", img_s);
        }
        new BaseInternet().getData(URLString.SERVICE_UP, hashMap, ForgetBean.class, new PostEvent<ForgetBean>(), false);
    }

    @EventAnnotation
    public void PostEvent(PostEvent<ForgetBean> event) {
        switch (event.getCode()) {
            case 200:
                T.showShort(this, event.getMsg());
                finish();
                break;
            default:
                SN.SnackShow(text_select, event.getMsg());
                break;
        }
    }


    @EventAnnotation
    public void FilebackEvent(FilebackEvent event) {
        file = event.getData();
    }

    @EventAnnotation
    public void FilebackEvent2(FilebackEvent2 event) {
        //file_name
        String[] img = event.getData().split("/");

        file_name = img[img.length - 1];
        handler.sendEmptyMessage(3000);
    }



    /**
     * 多图上传回调
     *
     * @param event
     */
    @EventAnnotation
    public void onEventPicGet(DuoTuEvent<String> event) {
        String img_duotu = event.getData();
        mList.clear();
        img_s = img_duotu;
        LsfbLog.e("多图上传:***" + img_s);
        String[] img = img_s.split(",");
        img_number=img.length;
        if (img.length == 1) {
            img_photo1.setVisibility(View.VISIBLE);
            img_photo2.setVisibility(View.INVISIBLE);
            img_photo3.setVisibility(View.INVISIBLE);
            img_photo1.setImageURI(Uri.parse(URLString.IMG_URL + img[0]));
            img1=img[0];
        }else if (img.length == 2) {
            img_photo1.setVisibility(View.VISIBLE);
            img_photo2.setVisibility(View.VISIBLE);
            img_photo3.setVisibility(View.INVISIBLE);
            img_photo1.setImageURI(Uri.parse(URLString.IMG_URL + img[0]));
            img_photo2.setImageURI(Uri.parse(URLString.IMG_URL + img[1]));
            img1=img[0];
            img2=img[1];
        }else if (img.length == 3) {
            img_photo1.setVisibility(View.VISIBLE);
            img_photo2.setVisibility(View.VISIBLE);
            img_photo3.setVisibility(View.VISIBLE);
            img_photo1.setImageURI(Uri.parse(URLString.IMG_URL + img[0]));
            img_photo2.setImageURI(Uri.parse(URLString.IMG_URL + img[1]));
            img_photo3.setImageURI(Uri.parse(URLString.IMG_URL + img[2]));
            img1=img[0];
            img2=img[1];
            img3=img[2];
        }


    }

    /**
     * 照片回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_CIR_IMAGE && resultCode == Activity.RESULT_OK
                && null != data) {
            // presenter.upImgHead(String.valueOf(xid), data);

            File file = LittleUtils.getImageToView(data);
            uploadimg(file);
        } else if (requestCode == LsfbCamera.REQUESTCODE && resultCode == RESULT_OK) {
//            uploadimg(new File(mUri.getPath()),1);

            File file = new File(mUri.getPath());
            File zipfile = ZipPic.zippng(mUri.getPath());

            List<File> lists = new ArrayList();
            lists.add(zipfile);

            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("uid",Config.getUserId());
            hashMap.put("img",lists.get(0).getPath());

            new HttpClient().postFile(URLString.IMGUPLOAD + LittleUtils.getToken(URLString.IMGUPLOAD), hashMap, lists, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    LsfbLog.e("照片上传成功");
                    String resultJson = response.body().string();
                    LsfbLog.e(resultJson);

                    try {
                        JSONObject jsonObject = new JSONObject(resultJson);
                        JSONObject img = jsonObject.getJSONObject("data");
                        String mimage = img.getString("img");

                        if (img_s==null){
                            GetPhoto(mimage);
                            img_s = mimage;
                        }else {
                            String[]  strs=img_s.split(".jpg");
                            if (strs.length>2){
                                SN.SnackShow(text_select,"最多只能上传3张照片");
                            }else {
                                GetPhoto(mimage);
                                img_s =img_s+","+ mimage;
                            }
                        }

//                        img_s = mimage;
                    } catch (JSONException e) {
                        e.printStackTrace();
                        LsfbLog.e("Json2解析错误"+e.getMessage());
                    }

                }
            });
        }
    }

    /**
     * 上传单个图片
     *
     * @param file
     */
    public void uploadimg(File file) {
        HttpClient client = new HttpClient();
        List<File> fileList = new ArrayList<File>();
        fileList.add(file);

        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("uid",Config.getUserId());
        hashMap.put("img",fileList.get(0).getPath());

        client.postFile(URLString.IMGUPLOAD + LittleUtils.getToken(URLString.IMGUPLOAD), hashMap, fileList, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                LsfbLog.e("上传错误");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                LsfbLog.e("上传成功");

                String reAddress = response.body().string();
                try {
                    JSONObject jsonObject = new JSONObject(reAddress);
                    String img_fm = jsonObject.getString("img");

                    if (img_number==0){
                        img_photo1.setVisibility(View.VISIBLE);
                        img_photo1.setImageURI(Uri.parse(URLString.IMG_URL + img_fm));
                        img1=img_fm;
                    }else if (img_number==1){
                        img_photo1.setVisibility(View.VISIBLE);
                        img_photo2.setImageURI(Uri.parse(URLString.IMG_URL + img_fm));
                        img2=img_fm;
                    }else if (img_number==2){
                        img_photo1.setVisibility(View.VISIBLE);
                        img_photo3.setImageURI(Uri.parse(URLString.IMG_URL + img_fm));
                        img3=img_fm;
                    }

                } catch (JSONException e) {
                    LsfbLog.e(Log.getStackTraceString(e));
                    e.printStackTrace();
                }

            }
        });
    }

    public void GetPhoto(final String url) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                if (img_number==0){
                    img_photo1.setVisibility(View.VISIBLE);
                    img_photo1.setImageURI(Uri.parse(URLString.IMG_URL + url));
                    img1=url;
                }else if (img_number==1){
                    img_photo1.setVisibility(View.VISIBLE);
                    img_photo2.setImageURI(Uri.parse(URLString.IMG_URL + url));
                    img2=url;
                }else if (img_number==2){
                    img_photo1.setVisibility(View.VISIBLE);
                    img_photo3.setImageURI(Uri.parse(URLString.IMG_URL + url));
                    img3=url;
                }

            }
        });
    }




}
